  function returnFloat(value){
     var value=Math.round(parseFloat(value)*100)/100;
     var xsd=value.toString().split(".");
     if(xsd.length==1){
     value=value.toString()+".00";
     return value;
     }
     if(xsd.length>1){
     if(xsd[1].length<2){
      value=value.toString()+"0";
     }
     return value;
     }
}
var _attrTotal = 0;
var attrItems = {};
$(document).ready(function() {
  $("body").on('tap',".popuplayout .spec-item",function(){
       var _this = $(this);
       _this.parent().find('span').removeClass('on');
       _this.addClass('on');
       var _num = 1;
       var itemOn = $('.popuplayout').find('.spec-item.on');
          var itemArr = new Array();   
          for (var i = 0;i<itemOn.length;i++) { 
              itemArr.push($(itemOn[i]).data('aid'));
          }
       $.post("/home/getItemSku",{product_id:$(this).data('product'),'itemArr':itemArr},function(result){
              selectdSpecKey = result.key;
              var _total = returnFloat(parseFloat(result.price)+_attrTotal);
              $("#_mprice").html("$"+_total+"");
              $("#_mprice").data('price',_total);
              if(result.num*1 > 0){
                  $(".addcartbtn").html('<p class="select"><a data-product="'+_this.data('product')+'" class="minus popup" data-role="none" href="javascript:void(0)">-</a><input class="number" data-role="none" type="text" name="product_num" value="'+result.num+'" readonly="readonly"><a class="add popup" data-role="none" href="javascript:void(0)" data-product="'+_this.data('product')+'">+</a></p>');
                  if(typeof result.attrs == 'object'){
                      $.each(result.attrs,function(k,val){
                          var attritembox = $(".attr-item[data-aid='"+k+"']");
                              attritembox.addClass('on');
                              attritembox.parent().find(".select").remove();
                              attritembox.parent().append('<em class="select"><a data-product="'+attritembox.data('product')+'" class="aminus popup" data-role="none" href="javascript:void(0)">-</a><input class="number attr_total" data-role="none" type="text" name="attrs['+k+']" value="'+val+'" readonly="readonly"><a class="aadd popup" data-role="none" href="javascript:void(0)" data-product="'+attritembox.data('product')+'">+</a></span>')
                      })
                  }
                  $('#_close').text('确定');
                  return false;
              }else{
                //$(".attr-item").removeClass('on');
                //$(".attr-item").parent().find(".select").remove();
                $('#_close').text('取消');
              }
              $("#cart_spec_key").val(selectdSpecKey);
              $("#_product_num").val(_num)
              $(".addcartbtn").html('<button class="push-cart" type="button" data-product="'+_this.data('product')+'">加入購物車</button>');
          },"json")
       return true;
       if(typeof jsonData == 'object'){
          $.each(jsonData,function(key,item){
              var keyArr = key.split("_");
              var result = minus(keyArr,itemArr);
              if(result.length == 0){
                  var _total = returnFloat(parseFloat(item.price)+_attrTotal);
                  $("#_mprice").html("$"+_total+"");
                  $("#_mprice").data('price',_total);
                  selectdSpecKey = key;
              }
          });
          
       }
       //$('#_close').text('确定');
       
  })
  $('body').on('tap',".push-cart",function(){
        pushCart($(this).data('product'),1,selectdSpecKey,$(this));
  })
  /*任意選擇屬性*/
  $("body").on('tap',".popuplayout .attr-item",function(){
       var _this = $(this);
       var _aid = _this.data('aid');
       var _spec = _this.data('spec');
       var _attrPrice = parseFloat($(this).data('price'));
       if(_this.hasClass('on')){
          _this.removeClass('on');
          _attrTotal -= _attrPrice*parseFloat(_this.parent().find("input.number").val());
          _this.parent().find('.select').remove();
       }else{
          _this.addClass('on');
          _attrTotal += _attrPrice;
          _this.parent().append('<em class="select"><a data-product="'+_this.data('product')+'" class="aminus popup " data-role="none" href="javascript:void(0)">-</a><input class="number attr_total" data-role="none" type="text" name="attrs['+_aid+']" value="1" readonly="readonly"><a class="aadd popup" data-role="none" href="javascript:void(0)" data-product="'+_this.data('product')+'">+</a></span>')
       }
       var _orderTotal = parseFloat($("#_mprice").data('price'));
       $("#_mprice").html("$"+returnFloat(_orderTotal+_attrTotal));
  })
  /*任意選擇屬性*/
  $("body").on('tap',".select a.aminus",function(){
       var _this = $(this);
       var _numObj = _this.parent().find('.number');
       if(parseInt(_numObj.val()) > 1){
          var _num =parseInt(_numObj.val())-1;
          _numObj.val(_num);
          /*处理价格*/
         var _attrDemo = $(this).parents(".attr_label").find('.attr-item.on');
         _attrTotal -= parseFloat(_attrDemo.data('price'));
         var _orderTotal = parseFloat($("#_mprice").data('price'));
         $("#_mprice").html("$"+returnFloat(_orderTotal+_attrTotal));
       }

  })
  /*任意選擇屬性*/
  $("body").on('tap',".select a.aadd",function(){
       var _this = $(this);
       var _numObj = _this.parent().find('.number');
       var _num =parseInt(_numObj.val())+1;
       _numObj.val(_num);
       /*处理价格*/
       var _attrDemo = $(this).parents(".attr_label").find('.attr-item.on');
       _attrTotal += parseFloat(_attrDemo.data('price'));
       var _orderTotal = parseFloat($("#_mprice").data('price'));
       $("#_mprice").html("$"+returnFloat(_orderTotal+_attrTotal));
  })
  var product_map={};
  //綁定點擊事件加入購物車
  $('body').on('click', '.add-cart-btn', function(e) {

     var _slef = $(this);
    e = e || window.event;
    e.preventDefault ? e.preventDefault() : e.returnValue = false;

    var eTarget = e.target || e.srcElement;
    var $eTarget=$(eTarget);
    if($eTarget.hasClass('minus') || $eTarget.hasClass('add')){
      return false;
    }
    var _item = $(this).parents('li');
    var product_id=_item.attr('product_id');
    if(_item.data('price') == 1){
        ajax_get_items(product_id)
        return false;
    }
    
    var copy=_item.clone(true);
    if(_item.find('.select').is(":visible")==false){
      _item.find('.select').show();
      _slef.hide();
      copy[0].id='cart_'+product_id;
      copy.find('.select').style='block';
      $("#cart_content").append(copy);
      product_map[product_id]=1;
      pushCart(product_id,1,0,$(this));
    }else{//刪除
      if( _item.find('input.number').val()*1 > 1){
          return false;
      }
      _item.find('input.number').val('1');
      _item.find('.select').hide();
      $('#cart_'+product_id).remove();
      delete product_map[product_id];//刪除存儲對象
      pushCart(product_id,0,0,$(this));
    }
    all_total();//調用更新
  });

  //綁定加減事件
  $('body').on('click','a.minus', function(e) {
    var _item = $(this).parents('li');
    var product_id=_item.attr('product_id');
    var product_num=$(this).parent().find('input.number').val();
    if($(this).hasClass('popup')){
        var product_id=$(this).data('product');
    }
    var spec_key = 0;
    if(product_id>0){
      var minus=parseInt(product_num)-1;
      if(minus>0){//還有數量
        //$(this).parent().find('input.number').val(minus);
        $(this).parent().find('input.number').val(minus);
        product_map[product_id]=minus;
        if($(this).hasClass('popup')){
           spec_key = selectdSpecKey;
        }
      }else{
        //$(this).parents('li').remove();
        if($(this).hasClass('cart')){
            _attrTotal = 0;
            $(this).parents('li').remove();
        }
        if($(this).hasClass('popup')){
           spec_key = selectdSpecKey;
           //$(".addcartbtn").html('<button class="push-cart" type="button" data-product="'+product_id+'">加入購物車</button>');
        }
        _item.find('input.number').val('1');
        _item.find('.select').hide();
        _item.find('.add-cart-btn').show();
        delete product_map[product_id];//刪除存儲對象
      }
      if($(this).hasClass('cart-list')){
          spec_key = $(this).data('spec');
      }
      pushCart(product_id,product_num-1,spec_key,$(this));
    }
    all_total();//調用更新
    e.cancelBubble = true;//取消事件冒泡
  });

  $('body').on('click', 'a.add', function(e) {
    var _item = $(this).parents('li');
    var product_id=_item.attr('product_id');
    var product_num=$(this).parent().find('input[name="product_num"]').val();
    var spec_key = 0;
    if($(this).hasClass('popup')){
         spec_key = selectdSpecKey;
        product_id=$(this).data('product');

    }
    if($(this).hasClass('cart-list')){
        spec_key = $(this).data('spec');
    }
    if(product_id>0 && product_num>0){
      var add_num=parseInt(product_num)+1;
      //$('li.product_'+product_id).find('input[name="product_num"]').val(add_num);
      //$('#cart_'+product_id).find('input[name="product_num"]').val(add_num);
      $(this).parent().find('input[name="product_num"]').val(add_num);
      product_map[product_id]=add_num;
      pushCart(product_id,add_num,spec_key,$(this));
    }
    all_total();//調用更新
    e.cancelBubble = true;//取消事件冒泡
  });

  //點擊購物車,顯示數量.
  $('a[href="#cart"]').click(function(){
    $("#cart_content").html('');
    
     $("#cart_content .select").show();
     get_cart_products();
  });
  get_cart_products();
  function get_cart_products(){
    $("#no_cart_product").show();
    $(".flat-bottom").hide();
      $.post($("#_get_cartList").val(),{},function(result){
            $(".cart_total").text(result.num);
            $(".total_price").text(result.total);
            $("#cart_total_num").val(result.num);
            if(result.data != null && result.data.length>0){
              var  data = result.data;
              for(var i=0;i<data.length;i++){
                  var html = '<li class="product product_'+data[i].id+'" data-spec="'+data[i].spec+'"  product_id="'+data[i].id+'" data-aid="'+data[i].id+'" data-price="0" id="cart_'+data[i].id+'_'+data[i].spec+'">';
                  html +='<div class="cover">';
                  html +='<figure class="cover_son" itemprop="associatedMedia" itemscope="">';
                  html += '<a id="gethref" href="'+data[i].main_image+'" itemprop="contentUrl" data-size="500x500" class="ui-link">';
                  html +='<img id="bigimages" src="'+data[i].main_image+'" itemprop="thumbnail" alt="Image description " width="100" height="100"></a></figure></div>';
                  html += '<p class="title">'+data[i].title+'</p>';
                  if(data[i].attrStr != null || data[i].attrStr != undefined){
                      html += '<p class="p-attrs">'+data[i].attrStr+'</p>';
                  }
                  html += '<p class="details">'+data[i].introduction+'</p>';
                  html += '<p class="price">$'+data[i].price+'/'+data[i].unit+'</p>';
                  html += '<p class="select">';
                  html += '<a class="minus cart cart-list"  data-spec="'+data[i].spec+'" data-role="none" href="javascript:void(0)">-</a>';
                  html += '<input class="price" data-role="none" type="hidden" name="product_price" value="'+data[i].price+'">';
                  html += '<input class="number" data-role="none" type="text" name="product_num" value="'+data[i].num+'" readonly="readonly">';
                  html += '<a class="add cart cart-list" data-spec="'+data[i].spec+'" data-role="none" href="javascript:void(0)">+</a>';
                  html += '</p>';
                  html += '<div class="clearfix"></div>';
                  html += '</li>';
                  $("#cart_content").append(html);
              }
              $("#no_cart_product").hide();
              $("#cart").find('.flat-bottom').show();
            }else{
               $(".flat-bottom").hide();
            }
      },"json")
  }
  //總數計算
  function all_total(){
    var total_price=0;
    var cart_total=0;
    if($("#cart_content li.product").length>0){
      $('#no_cart_product').hide();
      $("#cart .flat-bottom").show();
    }else{
      $('#no_cart_product').show();
      $("#cart .flat-bottom").hide();
    }
    $("#cart_content li.product").each(function() {
      var product_num=$(this).find('input.number').val();
      var product_price=$(this).find('input.price').val();
      product_price=parseFloat(product_price)*1;
      product_num=parseInt(product_num)*1;
      sub_total=parseFloat(product_price*product_num);
      cart_total = parseFloat(cart_total)+parseFloat(product_num);
      total_price = parseFloat(total_price)+(sub_total > 0 ?sub_total:0);
      
    });

    $('#cart_total_price').val(returnFloat(total_price));
    $('.total_price').text(returnFloat(total_price));

    $('#cart_total_num').val(cart_total);
    $('.cart_total').text(cart_total);

    // console.log(product_map);
    var product_string = obj2str(product_map);//轉換為字符串
    $('#product_string').val(product_string);
    console.log(product_string);

  }

  //發送訂單.
  $('a[href="#success"]').click(function(){
    if($(this).attr('disabled'))
      return false;
    $("#order_form input").removeClass('req-tips');
    $('#contact_phone_msg').text('*必填');
    var nickname=$("#nickname").val();
    var contact_phone=$("#contact_phone").val();
    var product_string=$("#product_string").val();
    var cart_total_num=$("#cart_total_num").val();
    if(cart_total_num<=0){
      alert('對不起,您的購物車是空的,不能提交!')
      return false;
    }
    if($('#table_num').val() == '' || $('#table_num').val() == null){
      alert('請輸入桌號.')
      
      return false;
    }
    var form_url=$("#order_form").attr('action');
    var form_data=$("#order_form").serialize();
    var form_method=$("#order_form").attr("method");
    $.ajax({
      type:form_method,
      data:form_data,
      dataType:'json',
      url:form_url,
      success:function(data){
        if(typeof data.msg === 'string' && data.codes == 3){
           $('body').append(data.msg );
           return true;
        }
        $('#order-loading').hide();
        $('a[href="#success"]').html('發送訂單').removeAttr('disabled').show();
        if($.isEmptyObject(data) || typeof data === 'string'){
           alert('對不起,網絡不流暢，請出現提交！');
        }

        if(typeof data.msg === 'string' && data.codes ==1){//提交成功
          $('#success_msg').html(data.msg).fadeIn();
          product_map={};//清空購物記錄
          $('#product_string').val('');
          $('#cart_content').html('');
          $('li.product').find('input.number').val('1');
          $('li.product').children('.select').hide();
          $("#order_form")[0].reset();
          all_total();//調用更新
          window.location.href='#success';
        }

        if(typeof data.msg === 'string' && data.codes !=1){
          alert(data.msg);
        }
      },
      beforeSend:function(){
        $('#order-loading').show();
        $('a[href="#success"]').html('提交中');
        $('a[href="#success"]').attr('disabled','disabled');
        $('a[href="#success"]').hide();
      },
      error:function(){
        alert('對不起,網絡不流暢，請出現提交.');
        $('#order-loading').hide();
        $('a[href="#success"]').html('發送訂單').removeAttr('disabled').show();
      }
    });
    return false;
  });

  //頁面訂單查詢跳頁,重置
  $('a[href="#search"]').click(function(){
    $('#search_detail').html('');
    $('#search_product').html('');
    $('#search_result').hide();
    $("#search_order").val('');
  });
  //訂單查詢
  $('a[href="#search-btn"]').click(function(){
    if($(this).attr('disabled'))
      return false;
    $("#order_form input").removeClass('req-tips');
    var search_order=$("#search_order").val();
    if(search_order==''){
      $("#search_order").addClass('req-tips').fadeOut().fadeIn();
      $("#search_order").focus();
      return false;
    }
    $('#search_detail').html('');
    $('#search_product').html('');
    $('#search_result').hide();
    var form_url=$("#form_search").attr('action');
    var form_data=$("#form_search").serialize();
    var form_method=$("#form_search").attr("method");
    $.ajax({
      type:form_method,
      data:form_data,
      dataType:'json',
      url:form_url,
      success:function(data){
        console.log(data);
        $('#search_product_list').show();
        $('a[href="#search-btn"]').html('查詢').removeAttr('disabled');
        if($.isEmptyObject(data) || typeof data === 'string'){
          $('#search_detail').html('沒有查詢到，請重新輸入正確的訂單號。');
          $('#search_product_list').hide();
        }
        if(typeof data.order_detail === 'string' && typeof data.order_product === 'string' && data.order_detail !=''){
          $('#search_detail').html(data.order_detail);
          $('#search_product').html(data.order_product);
        }
        $('#search_result').fadeIn();
      },
      beforeSend:function(){
        $('a[href="#search-btn"]').html('查詢中');
        $('a[href="#search-btn"]').attr('disabled','disabled');
      },
      error:function(){
        alert('對不起,order Ajax操作失敗!');
        $('a[href="#search-btn"]').html('搜索').removeAttr('disabled');
      }
    });
    return false;
  });

  //方式切換
  $('#order_way').change(function(){
    var way=$(this).val();
    if(way==1){
      $('#logistics').hide();
    }else{
      $('#logistics').show();
    }
  });
  
  //日期控件
  if($("#dtBox").length > 0){
      $("#dtBox").DateTimePicker({
        dateFormat: "yyyy-MM-dd",
        timeFormat: "hh:mm AA",
        dateTimeFormat: "yyyy-MM-dd hh:mm:ss AA",
        shortDayNames: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
        fullDayNames: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
        shortMonthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
        fullMonthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
        titleContentDateTime: "設定外賣送達時間",
        setButtonContent: "設定",
        clearButtonContent: "清除",
      });
    }
});
  $("body").on('click','._close',function(){
    $(".popup").remove();
    /*获取属性*/
    var attrItems = $(this).parents('.popuplayout').find(".attr-item.on");
    var attrs = {};
    var product_id = $(this).parents('.popuplayout').data('product')*1;
    if(attrItems != undefined && attrItems.length > 0){
        for(var a=0;a<attrItems.length;a++){
          if($(attrItems[a]).data('aid') *1>0 && $(attrItems[a]).parent().find('.attr_total').val()*1 > 0){
               attrs[$(attrItems[a]).data('aid')] = $(attrItems[a]).parent().find('.attr_total').val();
          }
        }
    }
    /*更新多选项属性*/
    if(product_id > 0){
       $.post("home/updateCartAttr",{'spec':selectdSpecKey,'product_id':product_id,attrs:attrs},function(result){

       });
    }
    return false;
  })
  //2个集合的差集 在arr不存在  
  function minus(arr,arr1) {  
    var result = new Array();  
    var obj = {};  
    for (var i = 0; i < arr.length; i++) {  
        obj[arr[i]] = 1;  
    }  
    for (var j = 0; j < arr1.length; j++) {  
        if (!obj[arr1[j]])  
        {  
            obj[arr1[j]] = 1;  
            result.push(arr1[j]);  
        }  
    }  
    return result;  
};  
/*加入购物车*/
function pushCart(product_id,num,spec_key,_this){
    if(_this.hasClass('cart-list')){  //是购物车页面
        var attrItems = _this.parents('li').find(".attr-item.on");
    }else{
        var attrItems = _this.parents('.popuplayout').find(".attr-item.on");
    }
    var attrs = {};
    if(attrItems != undefined && attrItems.length > 0){
        for(var a=0;a<attrItems.length;a++){
          if($(attrItems[a]).data('aid') *1>0 && $(attrItems[a]).parent().find('.attr_total').val()*1 > 0){
               attrs[$(attrItems[a]).data('aid')] = $(attrItems[a]).parent().find('.attr_total').val();
               //attrs.push(attr);
          }
        }
    }
    $.post($("#_add_cart").val(),{product_id:product_id,product_num:num,spec_key:spec_key,attrs:attrs},function(result){
        $('#cart_total_num').val(result.num);
        $('.cart_total').text(result.num);
        if(result.nownum>0){
            $(".addcartbtn").html('<p class="select"><a data-product="'+product_id+'" class="minus popup" data-role="none" href="javascript:void(0)">-</a><input class="number" data-role="none" type="text" name="product_num" value="'+result.nownum+'" readonly="readonly"><a class="add popup" data-role="none" href="javascript:void(0)" data-product="'+product_id+'">+</a></p>');
            $('#_close').html(_text1);
        }else{
            $(".addcartbtn").html('<button class="push-cart" type="button" data-product="'+product_id+'">加入購物車</button>');
          $('#_close').html(_text2);
          _attrTotal = 0;
        }
        nowCarts = result.cart;
  },'json')
}
/*加入购物车*/
function popupPushCart(){

    var product_id = $("#_product_id").val();
    $("#_pnum").val(parseInt($("#_product_num").val()));
    $.post($("#cart_form").attr('action'),$("#cart_form").serialize(),function(result){
          $('#cart_total_num').val(result.num);
          $('.cart_total').text(result.num);
          if(result.nownum>0){
            $(".addcartbtn").html('<p class="select"><a data-product="'+product_id+'" class="minus popup" data-role="none" href="javascript:void(0)">-</a><input class="number" data-role="none" type="text" name="product_num" value="'+result.nownum+'" readonly="readonly"><a class="add popup" data-role="none" href="javascript:void(0)" data-product="'+product_id+'">+</a></p>');
   
          }else{
            $(".addcartbtn").html('<p class="select"><a data-product="'+product_id+'" class="minus popup" data-role="none" href="javascript:void(0)">-</a><input class="number" data-role="none" type="text" name="product_num" value="'+1+'" readonly="readonly"><a class="add popup" data-role="none" href="javascript:void(0)" data-product="'+product_id+'">+</a></p>');
          }
          //$('#_close').text('确定');
          //all_total();//調用更新
          $(".popup").remove();
          nowCarts = result.cart;
    },'json')
}
$(function(){
  $(document).on('click', '#getimg', function() {
      var imgsrc = $(this).data("imgs");
      var imgurl = $(this).parent().data('link');
      $(this).parents("li").find('._bigimages').attr("src",imgsrc);
      $(this).parents("li").find('._gethref').attr('href',imgurl)
      return false;
  })
})
function ajax_get_items(product_id){
       PadeLoading();
      $.post($("#_popup_spec_item").val(),{product_id:product_id},function(result){
        _closeLoad()
          if(result.status == 1){
              jsonData = result.jsonData;
              selectdSpecKey = result.selectdSpecKey;
              attrItems = result.attrItems;
              $('body').append(result.html);
              
          }
      },"json");
  }

function PadeLoading(){

  $.PadeLoading({  // Options
     'BgColor' : '#000000',
     //'BgIMG' : 'URLOfBackgroundImage',
     'BgInnerColor' : '#FFFFFF',
     'BorderColor' : '#FFFFFF',
     'ShadowColor' : '#FFFFFF',
     'LoaderIMG' : "themes/front/img/ajax-loading.gif",
     'zIndex' : 999
    });
}
function _closeLoad(){
  $.PadeLoaded();
  $("#OverMask").remove();
  $("#LoaderDiv").remove();
}